import {ElMessage} from "element-plus";

// export function generateRandomNumbers(form) {
//     let {count, targetMean, targetStdDev, maxValue} = form
//     // targetMean,plusNum,minNum,maxValue
//     // const targetMean = 52.08;
//     // const targetStdDev = 10.76;
//     // const count = 41;
//     // const maxValue = 144;
//     let numbers = [];
//     let sum = 0;
//
//     // 生成符合正态分布的随机数
//     for (let i = 0; i < count; i++) {
//         let num;
//         do {
//             num = Math.round(normalRandom(targetMean, targetStdDev));
//         } while (num < 0 || num > maxValue);
//         numbers.push(num);
//         sum += num;
//     }
//
//     // 调整总和以精确匹配目标均值
//     const targetSum = Math.round(targetMean * count);
//     const diff = targetSum - sum;
//     if (diff !== 0) {
//         adjustNumbers(numbers, diff, maxValue);
//     }
//
//     // 打乱顺序
//     return shuffleArray(numbers);
// }
//
// function normalRandom(mean, stdDev) {
//     let u = 0, v = 0;
//     while (u === 0) u = Math.random();
//     while (v === 0) v = Math.random();
//     return mean + stdDev * Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
// }
//
// function adjustNumbers(arr, diff, maxValue) {
//     const step = diff > 0 ? 1 : -1;
//     let remaining = Math.abs(diff);
//
//     while (remaining > 0) {
//         const index = Math.floor(Math.random() * arr.length);
//         if ((step === 1 && arr[index] < maxValue) ||
//             (step === -1 && arr[index] > 0)) {
//             arr[index] += step;
//             remaining--;
//         }
//     }
// }
//
// function shuffleArray(array) {
//     for (let i = array.length - 1; i > 0; i--) {
//         const j = Math.floor(Math.random() * (i + 1));
//         [array[i], array[j]] = [array[j], array[i]];
//     }
//     return array;
// }

// // 生成并输出结果
// const result = generateRandomNumbers();
// console.log(result.join('\n'));

// export function generateRandomNumbers(form) {
//     let {count, targetMean, targetStdDev, maxValue, decimalPlaces = 0} = form
//
//     // const targetMean = 52.08;
//     // const targetStdDev = 10.76;
//     // const count = 41;
//     let numbers = [];
//     let sum = 0;
//
//     // 生成符合正态分布的随机数
//     for (let i = 0; i < count; i++) {
//         let num;
//         do {
//             num = normalRandom(targetMean, targetStdDev);
//             num = parseFloat(num.toFixed(decimalPlaces));
//         } while (num < 0 || (maxValue && num > maxValue));
//         numbers.push(num);
//         sum += num;
//     }
//
//     // 调整总和以精确匹配目标均值
//     const targetSum = parseFloat((targetMean * count).toFixed(decimalPlaces));
//     const diff = parseFloat((targetSum - sum).toFixed(decimalPlaces));
//     if (diff !== 0) {
//         adjustNumbers(numbers, diff, maxValue, decimalPlaces);
//     }
// // .join('\n');
//     // 打乱顺序并格式化为每行一个数字
//     return shuffleArray(numbers)
// }
//
// function normalRandom(mean, stdDev) {
//     let u = 0, v = 0;
//     while(u === 0) u = Math.random();
//     while(v === 0) v = Math.random();
//     return mean + stdDev * Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
// }
//
// function adjustNumbers(arr, diff, maxValue, decimalPlaces) {
//     const step = diff > 0 ? 1 : -1;
//     let remaining = Math.abs(diff);
//     const adjustment = parseFloat(Math.pow(0.1, decimalPlaces).toFixed(decimalPlaces));
//
//     while (remaining > 0) {
//         const index = Math.floor(Math.random() * arr.length);
//         const newValue = parseFloat((arr[index] + step * adjustment).toFixed(decimalPlaces));
//
//         if ((step === 1 && (!maxValue || newValue <= maxValue)) ||
//             (step === -1 && newValue >= 0)) {
//             remaining = parseFloat((remaining - adjustment).toFixed(decimalPlaces));
//             arr[index] = newValue;
//         }
//     }
// }
//
// function shuffleArray(array) {
//     for (let i = array.length - 1; i > 0; i--) {
//         const j = Math.floor(Math.random() * (i + 1));
//         [array[i], array[j]] = [array[j], array[i]];
//     }
//     return array;
// }
export function generateRandomNumbers(form) {
    let { count, targetMean, targetStdDev, maxValue, decimalPlaces = 0 } = form;
    const factor = Math.pow(10, decimalPlaces); // 处理小数精度的系数
    const minSumRaw = targetMean * count; // 原始目标总和
    // 修正：确保总和严格大于 targetMean*count（避免浮点误差）
    const minSumScaled = Math.floor(minSumRaw * factor) + 1; // 关键改进点1
    const targetSum = minSumScaled / factor; // 最终目标总和（严格大于原始目标）
    const targetAvg = targetSum / count; // 目标平均值（>targetMean）

    let numbers;
    do {
        numbers = [];
        let sum = 0;

        const roundToDecimal = (num) => {
            return Math.round(num * factor) / factor;
        };

        // 生成初始随机数（正态分布，标准差为目标的80%以提高集中性）
        for (let i = 0; i < count; i++) {
            let num;
            do {
                num = normalRandom(targetMean, targetStdDev * 0.8);
                num = roundToDecimal(num);
            } while (num < 0 || (maxValue !== undefined && num > maxValue));
            numbers.push(num);
            sum += num;
        }

        // 调整总和至目标总和（严格等于targetSum）
        const diff = roundToDecimal(targetSum - sum);
        if (diff !== 0) {
            adjustNumbers(numbers, diff, maxValue, decimalPlaces);
        }

        // 降低标准差至目标以下
        reduceStdDev(numbers, targetStdDev, targetAvg, maxValue, decimalPlaces);

    } while (sampleStdDev(numbers) >= targetStdDev); // 确保标准差严格小于目标

    return shuffleArray(numbers).map(n => n.toFixed(decimalPlaces));
}

// 生成正态分布随机数（保留原逻辑）
function normalRandom(mean, stdDev) {
    let u = 0, v = 0;
    while (u === 0) u = Math.random();
    while (v === 0) v = Math.random();
    return mean + stdDev * Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
}

// 调整总和（增加范围校验，保留原逻辑核心）
function adjustNumbers(arr, diff, maxValue, decimalPlaces) {
    const step = diff > 0 ? 1 : -1;
    let remaining = Math.abs(diff);
    const adjustment = Math.pow(0.1, decimalPlaces);

    while (remaining > 0) {
        const index = Math.floor(Math.random() * arr.length);
        const originalVal = arr[index];
        const newValue = parseFloat((originalVal + step * adjustment).toFixed(decimalPlaces));

        // 校验新值是否在有效范围
        if ((step === 1 && (maxValue === undefined || newValue <= maxValue)) ||
            (step === -1 && newValue >= 0)) {
            remaining = parseFloat((remaining - adjustment).toFixed(decimalPlaces));
            arr[index] = newValue;
        }
    }
}

// 计算样本标准差（保留原逻辑）
function sampleStdDev(arr) {
    const n = arr.length;
    if (n < 2) return 0;
    const mean = arr.reduce((a, b) => a + b, 0) / n;
    const squaredDiffs = arr.map(x => Math.pow(x - mean, 2));
    const variance = squaredDiffs.reduce((a, b) => a + b, 0) / (n - 1);
    return Math.sqrt(variance);
}

// 降低标准差（增加范围校验，关键改进点2）
function reduceStdDev(arr, targetStdDev, mean, maxValue, decimalPlaces) {
    const count = arr.length;
    if (count < 2) return;
    const adjustmentStep = Math.pow(0.1, decimalPlaces);
    let currentStdDev = sampleStdDev(arr);

    while (currentStdDev >= targetStdDev) {
        const larger = arr.map((val, idx) => ({ val, idx })).filter(x => x.val > mean);
        const smaller = arr.map((val, idx) => ({ val, idx })).filter(x => x.val < mean);

        if (larger.length === 0 || smaller.length === 0) break;

        const large = larger[Math.floor(Math.random() * larger.length)];
        const small = smaller[Math.floor(Math.random() * smaller.length)];

        const maxReduce = large.val - mean;
        const maxIncrease = mean - small.val;
        const adjustAmount = Math.min(maxReduce, maxIncrease, adjustmentStep);

        if (adjustAmount <= 0) continue;

        // 校验调整后的大数值是否有效
        const newValLarge = large.val - adjustAmount;
        if (!(newValLarge >= 0 || (maxValue !== undefined && newValLarge <= maxValue))) {
            continue;
        }

        // 校验调整后的小数值是否有效
        const newValSmall = small.val + adjustAmount;
        if (!(newValSmall >= 0 || (maxValue !== undefined && newValSmall <= maxValue))) {
            continue;
        }

        // 执行调整
        arr[large.idx] = parseFloat(newValLarge.toFixed(decimalPlaces));
        arr[small.idx] = parseFloat(newValSmall.toFixed(decimalPlaces));

        currentStdDev = sampleStdDev(arr);
    }
}

// 打乱数组（保留原逻辑）
function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}export function generateRandomNumbers(form) {
    let { count, targetMean, targetStdDev, maxValue, decimalPlaces = 0 } = form;
    const factor = Math.pow(10, decimalPlaces); // 处理小数精度的系数
    const minSumRaw = targetMean * count; // 原始目标总和
    // 修正：确保总和严格大于 targetMean*count（避免浮点误差）
    const minSumScaled = Math.floor(minSumRaw * factor) + 1; // 关键改进点1
    const targetSum = minSumScaled / factor; // 最终目标总和（严格大于原始目标）
    const targetAvg = targetSum / count; // 目标平均值（>targetMean）

    let numbers;
    do {
        numbers = [];
        let sum = 0;

        const roundToDecimal = (num) => {
            return Math.round(num * factor) / factor;
        };

        // 生成初始随机数（正态分布，标准差为目标的80%以提高集中性）
        for (let i = 0; i < count; i++) {
            let num;
            do {
                num = normalRandom(targetMean, targetStdDev * 0.8);
                num = roundToDecimal(num);
            } while (num < 0 || (maxValue !== undefined && num > maxValue));
            numbers.push(num);
            sum += num;
        }

        // 调整总和至目标总和（严格等于targetSum）
        const diff = roundToDecimal(targetSum - sum);
        if (diff !== 0) {
            adjustNumbers(numbers, diff, maxValue, decimalPlaces);
        }

        // 降低标准差至目标以下
        reduceStdDev(numbers, targetStdDev, targetAvg, maxValue, decimalPlaces);

    } while (sampleStdDev(numbers) >= targetStdDev); // 确保标准差严格小于目标

    return shuffleArray(numbers).map(n => n.toFixed(decimalPlaces));
}

// 生成正态分布随机数（保留原逻辑）
function normalRandom(mean, stdDev) {
    let u = 0, v = 0;
    while (u === 0) u = Math.random();
    while (v === 0) v = Math.random();
    return mean + stdDev * Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
}

// 调整总和（增加范围校验，保留原逻辑核心）
function adjustNumbers(arr, diff, maxValue, decimalPlaces) {
    const step = diff > 0 ? 1 : -1;
    let remaining = Math.abs(diff);
    const adjustment = Math.pow(0.1, decimalPlaces);

    while (remaining > 0) {
        const index = Math.floor(Math.random() * arr.length);
        const originalVal = arr[index];
        const newValue = parseFloat((originalVal + step * adjustment).toFixed(decimalPlaces));

        // 校验新值是否在有效范围
        if ((step === 1 && (maxValue === undefined || newValue <= maxValue)) ||
            (step === -1 && newValue >= 0)) {
            remaining = parseFloat((remaining - adjustment).toFixed(decimalPlaces));
            arr[index] = newValue;
        }
    }
}

// 计算样本标准差（保留原逻辑）
function sampleStdDev(arr) {
    const n = arr.length;
    if (n < 2) return 0;
    const mean = arr.reduce((a, b) => a + b, 0) / n;
    const squaredDiffs = arr.map(x => Math.pow(x - mean, 2));
    const variance = squaredDiffs.reduce((a, b) => a + b, 0) / (n - 1);
    return Math.sqrt(variance);
}

// 降低标准差（增加范围校验，关键改进点2）
function reduceStdDev(arr, targetStdDev, mean, maxValue, decimalPlaces) {
    const count = arr.length;
    if (count < 2) return;
    const adjustmentStep = Math.pow(0.1, decimalPlaces);
    let currentStdDev = sampleStdDev(arr);

    while (currentStdDev >= targetStdDev) {
        const larger = arr.map((val, idx) => ({ val, idx })).filter(x => x.val > mean);
        const smaller = arr.map((val, idx) => ({ val, idx })).filter(x => x.val < mean);

        if (larger.length === 0 || smaller.length === 0) break;

        const large = larger[Math.floor(Math.random() * larger.length)];
        const small = smaller[Math.floor(Math.random() * smaller.length)];

        const maxReduce = large.val - mean;
        const maxIncrease = mean - small.val;
        const adjustAmount = Math.min(maxReduce, maxIncrease, adjustmentStep);

        if (adjustAmount <= 0) continue;

        // 校验调整后的大数值是否有效
        const newValLarge = large.val - adjustAmount;
        if (!(newValLarge >= 0 || (maxValue !== undefined && newValLarge <= maxValue))) {
            continue;
        }

        // 校验调整后的小数值是否有效
        const newValSmall = small.val + adjustAmount;
        if (!(newValSmall >= 0 || (maxValue !== undefined && newValSmall <= maxValue))) {
            continue;
        }

        // 执行调整
        arr[large.idx] = parseFloat(newValLarge.toFixed(decimalPlaces));
        arr[small.idx] = parseFloat(newValSmall.toFixed(decimalPlaces));

        currentStdDev = sampleStdDev(arr);
    }
}

// 打乱数组（保留原逻辑）
function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}



export function generateRandomCancerTypes(cancers) {
    // Fisher-Yates洗牌算法实现随机排序
    for (let i = cancers.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [cancers[i], cancers[j]] = [cancers[j], cancers[i]];
    }

    // 转换为每行一个元素的文本格式
    return cancers
}

export function copyValue(value) {
    try {
        // 创建一个临时的输入框来存储文本
        const input = document.createElement('textarea');
        input.value = value;
        // 将输入框添加到页面，但不显示
        document.body.appendChild(input);
        input.select(); // 选择输入框的内容
        // 执行复制操作
        const isSuccessful = document.execCommand('copy');
        // 清除临时输入框
        document.body.removeChild(input);
        ElMessage({
            message: `复制成功`,
            duration: 2000,
            type: 'success',
        })
    } catch (err) {
    }
}

// 输出结果
// console.log(generateRandomCancerTypes());